import re
import tkinter as tk
from tkinter import filedialog
import pandas as pd
import os

def select_input_folder_path():
    """选择输入文件夹路径"""
    root = tk.Tk()
    root.withdraw()
    folder_path = filedialog.askdirectory(title="选择包含txt文件的文件夹")
    return folder_path

def select_output_file_path():
    """选择输出文件路径"""
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.asksaveasfilename(
        title="选择excel文件保存位置",
        defaultextension=".xlsx",
        filetypes=[("xlsx files", "*.xlsx"), ("All files", "*.*")],
    )
    return file_path

def read_logs(file_path):
    """从文件中读取日志"""
    try:
        with open(file_path, "r", encoding="utf-8") as file:
            logs = file.readlines()
        return logs
    except Exception as e:
        print(f"读取文件失败: {e}")
        return []

def analyze_logs(logs):
    """分析日志并统计结果"""
    # 正则表达式匹配完整的基站记录
    pattern = re.compile(r'^\w+\[-?\d+\.\d+,-?\d+\.\d+,-?\d+\.\d+\]=-?\d+\.\d+$')
    est_count = 0
    no_est_counts = {1: 0, 2: 0, 3: 0, 4: 0}  # 统计没有est时，每行中1、2、3、4个完整基站的数量

    for log in logs:
        log = log.strip()
        if not log:  # 跳过空行
            continue

        # 如果该行包含est，则计入est_count
        if 'est' in log:
            est_count += 1
            continue  # 跳过后续检查

        # 如果不包含est，则检查基站记录的完整性
        parts = log.split()
        valid = True
        for part in parts:
            if not pattern.fullmatch(part):
                valid = False
                break

        if valid:
            # 统计有效基站数量
            count = len(parts)
            if count in no_est_counts:
                no_est_counts[count] += 1

    return est_count, no_est_counts

def save_results(output_path, results):
    """将结果保存到Excel文件"""
    try:
        data = {
            "文件名": [],
            "产生坐标的数量": [],
            "连接1个基站": [],
            "连接2个基站": [],
            "连接3个基站": [],
            "连接4个基站": [],
        }

        for file_name, (est_count, no_est_counts) in results.items():
            # 去掉文件名中的 .txt 后缀
            file_name_without_extension = os.path.splitext(file_name)[0]
            data["文件名"].append(file_name_without_extension)
            data["产生坐标的数量"].append(est_count)
            data["连接1个基站"].append(no_est_counts[1])
            data["连接2个基站"].append(no_est_counts[2])
            data["连接3个基站"].append(no_est_counts[3])
            data["连接4个基站"].append(no_est_counts[4])

        df = pd.DataFrame(data)
        df.to_excel(output_path, index=False)
        print(f"结果已保存到: {output_path}")
    except Exception as e:
        print(f"保存文件失败: {e}")

def main():
    # 选择输入文件夹
    input_folder = select_input_folder_path()
    if not input_folder:
        print("未选择输入文件夹，程序退出。")
        return

    # 获取文件夹中所有txt文件
    txt_files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
    if not txt_files:
        print("文件夹中没有txt文件，程序退出。")
        return

    # 分析每个txt文件
    results = {}
    for txt_file in txt_files:
        file_path = os.path.join(input_folder, txt_file)
        logs = read_logs(file_path)
        if logs:
            est_count, no_est_counts = analyze_logs(logs)
            results[txt_file] = (est_count, no_est_counts)
            print(f"文件: {txt_file}")
            print(f"产生坐标的数量: {est_count}")
            print("没有坐标时，每行中完整基站记录的数量统计:")
            for count, num in no_est_counts.items():
                print(f"{count}个基站的数量: {num}")
            print("-" * 40)

    # 选择输出文件
    output_file = select_output_file_path()
    if not output_file:
        print("未选择输出文件，程序退出。")
        return

    # 保存结果
    save_results(output_file, results)

if __name__ == "__main__":
    main()